/*
 * QueueMux.cpp
 *
 */

#include "../../common/StringUtils.h"
#include "../../common/Argv.h"
#include "../../logger/logger.h"
#include "../../IPC/SizedMessageQueue.h"
#include "../../channel_common/AgentIdManager.h"
#include "../../channel_common/ChannelCommon.h"
#include "../../channel_common/ChannelInterface.h"
#include "../../channel_common/routing_tables/RoutingService.h"

int main(int argc, char **argv)
{
	char buffer[TAM_BUFFER];
	bool doRun=true;

	//Toma argumentos (main)
	Argv args(argv);

	if (args.getArgc() != 6)
	{
		std::cerr <<"Demux queue Error: Cantidad de parametros invalida"<<std::endl;
		exit(1);
	}

	//Args: ChannelName, QueuePath, QueueKey,size, mtype get
	std::string hostName = args.getArg(1);
	std::string queuePath = args.getArg(2);
	char queueKey  = args.getArg(3)[0];
	size_t packetSize = args.getArgAsInt(4);
	int mTypeApp = args.getArgAsInt(5);
	std::string destino;

	CLogger::create("Message queue DEMUX:"+queuePath+" mtype:"+
			         StringUtils::NumberToString(mTypeApp));

	try{
		channel::ChannelInterface communicationQueue(channel::ChannelInterface::RECEIVER, hostName);

		ipc::SizedMessageQueue outQueue(ipc::SizedMessageQueue::get(queuePath, queueKey));

		CLogger::log("Demux para mtype:"+StringUtils::NumberToString(mTypeApp),LogLevelEnum::INFO);

		channel::RoutingService::registerAgent(hostName,StringUtils::NumberToString(mTypeApp));

		while(doRun)
		{
			communicationQueue.recv(mTypeApp,buffer,packetSize);

			CLogger::log("Demultiplexando mensaje de tamaño:"+StringUtils::NumberToString(packetSize)
			+" contenido"+StringUtils::toHexaString(buffer,packetSize),LogLevelEnum::INFO);

			outQueue.put(mTypeApp,buffer,packetSize);
		}

	}
	catch(Exception&e)
	{
		CLogger::log("Exception:"+e.what_str(),LogLevelEnum::FATAL);
		exit(1);
	}

	CLogger::log("Finalizando",LogLevelEnum::INFO);
	return 0;
}
